<?php

namespace app\payment\admin;

use app\common\builder\ZBuilder;
use app\payment\model\PaymentRedis as RedisModel;
use app\payment\model\PaymentPayCompany as PaymentPayCompanyModel;
use app\payment\model\PaymentWithdrawalCompany as PaymentWithdrawalCompanyModel;
use app\payment\model\PaymentPaidCompany as PaymentPaidCompanyModel;
use app\payment\model\PaymentGoodCompany as PaymentGoodCompanyModel;
use app\payment\model\PaymentGoodPaidCompany as PaymentGoodPaidCompanyModel;
use app\payment\model\Mconfig as MconfigModel;
use app\api\model\PaymentOrderPaid;
use app\api\model\PaymentOrderAlipayPaid;
use think\facade\Cache;

/**
 * redis配置控制器
 */
class Redis extends Index
{

    protected $redis;
    protected $file;

    public function initialize()
    {
        parent::initialize();
        if ($this->no_auth) {
            $this->error('权限不足！');
        }

        if (in_array(request()->action(), ['add'])) {
            if (!$this->add_safe) {
                $this->error('NO');
            }
        }
        if (in_array(request()->action(), ['edit'])) {
            if (!$this->edit_safe) {
                $this->error('NO');
            }
        }
        if (in_array(request()->action(), ['delete'])) {
            if (!$this->delete_safe) {
                $this->error('NO');
            }
        }
        if (in_array(request()->action(), ['see'])) {
            if (!$this->key_see_safe) {
                $this->error('NO');
            }
        }

        // redis连接缓存驱动
        $this->redis = Cache::store('redis');
        // 文件连接缓存驱动
        $this->file = Cache::store('file');
    }

    /**
     * 首页
     * @return mixed
     */
    public function index()
    {
        // 设置搜索参数
        $search = ['name' => '名称', 'title' => '标题', 'value' => '值', 'status' => '状态'];

        // 获取查询条件
        $map = $this->getMap();
        // 排序
        $order = $this->getOrder('sort asc,title asc');
        $list_rows = input('list_rows', 200);
        // 数据列表
        $data_list = RedisModel::where($map)->order($order)->paginate($list_rows);

        // 分页数据
        $page = $data_list->render();
        // 更新redis数据库
        $btn_sql = [
            'title' => '更新redis数据库',
            'class' => 'btn btn-lg btn-success',
            'href' => url('sql')
        ];
        // 更新redis缓存
        $btn_redis = [
            'title' => '更新redis和文件缓存',
            'class' => 'btn btn-lg btn-warning',
            'href' => url('redisUp')
        ];
        // 更新redis数据库和更新redis缓存
        $redis_sql = [
            'title' => '同时更新redis数据库和文件缓存',
            'class' => 'btn btn-lg btn-primary',
            'href' => url('sql', ['redisUp' => 1, 'paidCashUp' => 0])
        ];
        // 清空redis缓存
        $btn_redis_clear = [
            'title' => '清空redis和文件缓存',
            'class' => 'btn btn-lg btn-default',
            'href' => url('clear'),
            'data-title' => '真的要清空redis和文件缓存吗？',
            'data-tips' => '清空后,请立即点击：同时更新redis数据库和文件缓存，否则任何api接口都无法使用'
        ];

        $items = [
            ['name', '名称'],
            ['title', '标题'],
            ['create_time', '创建时间', 'datetime', '', 'Y-m-d H:i:s'],
            ['update_time', '更新时间', 'datetime', '', 'Y-m-d H:i:s'],
            ['status', '状态', 'switch'],
            ['sort', '排序', 'text.edit'],
            ['right_button', '操作', 'btn']
        ];

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('redis管理') // 设置页面标题
            ->setTableName('payment_redis') // 设置数据表名
            ->setPrimaryKey('id') // 设置主键名为id
            ->setSearch($search) // 设置搜索参数
            ->addColumns($items)
            ->addRightButton('see', ['title' => '查看', 'icon' => 'fa fa-fw fa-eye', 'href' => url('see', ['id' => '__id__'], true)])
            ->addRightButton('update', ['title' => '更新', 'icon' => 'fa fa-fw fa-legal', 'href' => url('update', ['id' => '__id__'])])
            ->addTopButton('delete') // 添加顶部按钮
            ->addRightButtons('delete') // 批量添加右侧按钮
            //->addTopButton('sql', $btn_sql) // 更新redis数据库按钮
            //->addTopButton('redis', $btn_redis) // 更新redis缓存按钮
            ->addTopButton('redis_sql', $redis_sql) // 更新redis缓存按钮
            //->addTopButton('btn_redis_clear', $btn_redis_clear) // 清空redis缓存按钮
            ->setRowList($data_list) // 设置表格数据
            ->setPages($page) // 设置分页数据
            ->setPageTips('非开发者请勿随意操作')
            ->fetch(); // 渲染页面
    }

    /**
     * 清空数据库redis缓存
     */
    public function clear()
    {
        if ($this->role != 1) {
            $this->error('只允许超级管理员执行此操作！');
        }

        // 保存数据
        if ($this->request->isPost()) {
            $data = $this->request->post();

            if ($this->merchant_info['trade_pwd'] != md5(md5(md5($data['trade_pwd'])))) {
                $this->error('交易密码不正确！');
            }

            unset($data['trade_pwd']);

            // 清空redis
            $this->redis->clear();
            // 清空文件缓存
            //$this->file->clear();
            action_log('payment_redis_clear', 'payment_redis', '', UID, '清空了redis缓存');
            $this->success('清空完成', url('index'));
        }

        $items = [
            ['password', 'trade_pwd', '交易密码', '6-16位'],
        ];

        // 使用ZBuilder快速创建表单
        return ZBuilder::make('form')
            ->setPageTitle('查看') // 设置页面标题
            ->addFormItems($items)
            ->isAjax(false)
            ->fetch();
    }

    /**
     * 查看
     * @param null $id 
     * @return mixed
     */
    public function see($id = null)
    {
        if ($id === null) {
            $this->error('缺少参数！');
        }

        // 保存数据
        if ($this->request->isPost()) {
            $data = $this->request->post();

            if ($this->merchant_info['trade_pwd'] != md5(md5(md5($data['trade_pwd'])))) {
                $this->error('交易密码不正确！');
            }

            unset($data['trade_pwd']);

            // 获取数据
            $info = RedisModel::where('id', $id)->field(true)->find();
            if (!$info) {
                $this->error('不存在！');
            }
            $info['value'] = format_nice($info['value']);
            $items = [
                ['static', 'name', '名称'],
                ['static', 'title', '标题'],
                ['textarea', 'value', '值', '', '', '', ''],
                ['switch', 'status', '状态'],
                ['datetime', 'create_time', '创建时间', '', '', 'YYYY-MM-DD HH:mm:ss', 'disabled'],
                ['datetime', 'update_time', '更新时间', '', '', 'YYYY-MM-DD HH:mm:ss', 'disabled'],
            ];
            if ($this->role > $this->have_auth) {
                unset($items[2]);
            }
            // 使用ZBuilder快速创建表单
            return ZBuilder::make('form')
                ->setPageTitle('查看') // 设置页面标题
                ->setPageTips("说明：信息展示。")
                ->addFormItems($items)
                ->hideBtn('submit')
                ->setFormData($info) // 设置表单数据
                ->fetch();
        }

        $items = [
            ['password', 'trade_pwd', '交易密码', '6-16位'],
        ];

        // 使用ZBuilder快速创建表单
        return ZBuilder::make('form')
            ->setPageTitle('查看') // 设置页面标题
            ->addFormItems($items)
            ->isAjax(false)
            ->fetch();
    }

    /**
     * 更新数据库redis
     */
    public function sql($redisUp = false, $paidCashUp = false)
    {
        // 保存数据
        if ($this->request->isPost()) {
            $data = $this->request->post();

            if ($this->merchant_info['trade_pwd'] != md5(md5(md5($data['trade_pwd'])))) {
                $this->error('交易密码不正确！');
            }

            unset($data['trade_pwd']);

            // 查询已经配置完成的商户支付配置
            $merchant_config = MconfigModel::column('*', 'id');

            // 把商户的配置中值为json的数据转换成数组
            foreach ($merchant_config as $k => &$v) {
                // 商户提供的支付类型
                if (!empty($v['payment_type'])) {
                    $v['payment_type'] = json_decode($v['payment_type'], true);
                }
                // 商户提供的交易类型
                if (!empty($v['trade_type'])) {
                    $v['trade_type'] = json_decode($v['trade_type'], true);
                }
                // 支付类型和支付公司配置
                if (!empty($v['type_company_config'])) {
                    $v['type_company_config'] = json_decode($v['type_company_config'], true);
                }
                // VIP支付类型和支付公司配置
                if (!empty($v['vip_type_company_config'])) {
                    $v['vip_type_company_config'] = json_decode($v['vip_type_company_config'], true);
                }
                // 银行卡代付配置
                if (!empty($v['paid_company_config'])) {
                    $v['paid_company_config'] = json_decode($v['paid_company_config'], true);
                }
                // 支付宝代付配置
                if (!empty($v['alipay_paid_company_config'])) {
                    $v['alipay_paid_company_config'] = json_decode($v['alipay_paid_company_config'], true);
                }
                // 每次最小支付金额
                if (!empty($v['min_recharge_cash'])) {
                    $v['min_recharge_cash'] = json_decode($v['min_recharge_cash'], true);
                }
                // 每次最大支付金额
                if (!empty($v['max_recharge_cash'])) {
                    $v['max_recharge_cash'] = json_decode($v['max_recharge_cash'], true);
                }
                // 支付类型费率
                if (!empty($v['payment_type_rate'])) {
                    $v['payment_type_rate'] = json_decode($v['payment_type_rate'], true);
                }
                // 支付类型对应支付公司轮循开关
                if (!empty($v['pay_polling_open'])) {
                    $v['pay_polling_open'] = json_decode($v['pay_polling_open'], true);
                }
                // 支付类型每天最多充值金额总数
                if (!empty($v['day_recharge_type_cash_sum'])) {
                    $v['day_recharge_type_cash_sum'] = json_decode($v['day_recharge_type_cash_sum'], true);
                }

                // 服务端充值IP白名单
                $v['pay_ip'] = $v['pay_ip'] ? explode(',', $v['pay_ip']) : '';
                // 服务端提现IP白名单
                $v['withdrawal_ip'] = $v['withdrawal_ip'] ? explode(',', $v['withdrawal_ip']) : '';
                // 服务端代付IP白名单
                $v['paid_ip'] = $v['paid_ip'] ? explode(',', $v['paid_ip']) : '';

                // 商户所有的应用id
                $v['app_id'] = merchant_appid($k);
                // 商户名称
                $v['title'] = get_user_nickname($k);
            }

            // 存在更新数据库，插入数据库,商户支付配置
            $sort = 100;
            foreach ($merchant_config as $key => $value) {
                $payment_redis = RedisModel::where(['name' => $key])->field(true)->find();
                if ($payment_redis) {
                    $update = RedisModel::where(['name' => $key])->update(['title' => get_user_nickname($key), 'value' => json_encode($value), 'sort' => $sort++, 'update_time' => time()]);
                } else {
                    $insert = RedisModel::create(['name' => $key, 'title' => get_user_nickname($key), 'value' => json_encode($value), 'sort' => $sort++, 'create_time' => time(), 'update_time' => time(), 'status' => $value['status']]);
                }
            }

            // 获取配置分组
            $config_group = pay_config('config_group');

            // 分组配置值
            foreach ($config_group as $key => $value) {
                $company[$key] = pay_config('', $key);
                $company[$key]['title'] = $value;
            }

            // 删除支付设置    
            if (isset($company['pay_config'])) {
                unset($company['pay_config']);
            }

            // 存在更新数据库，插入数据库,各个支付公司配置
            $sort = 200;
            foreach ($company as $key => $value) {
                $payment_redis = RedisModel::where(['name' => $key])->field(true)->find();
                if ($payment_redis) {
                    $update = RedisModel::where(['name' => $key])->update(['title' => $value['title'], 'value' => json_encode($value), 'sort' => $sort++, 'update_time' => time()]);
                } else {
                    $insert = RedisModel::create(['name' => $key, 'title' => $value['title'], 'value' => json_encode($value), 'sort' => $sort++, 'create_time' => time(), 'update_time' => time(), 'status' => $value['status']]);
                }
            }

            // 查询已经配置完成的支付公司子商户支付配置
            $payment_pay_company = PaymentPayCompanyModel::where([])->order(['group' => 'asc', 'sort' => 'asc', 'title' => 'asc', 'name' => 'asc'])->column('*', 'name');

            // 存在更新数据库，插入数据库,支付公司子商户支付配置
            $sort = 300;
            foreach ($payment_pay_company as $key => &$value) {

                // 提供的支付类型
                if (!empty($value['payment_type'])) {
                    $value['payment_type'] = json_decode($value['payment_type'], true);
                }
                // 支付类型每天最多充值金额总数
                if (!empty($value['day_recharge_type_cash_sum'])) {
                    $value['day_recharge_type_cash_sum'] = json_decode($value['day_recharge_type_cash_sum'], true);
                }
                // 支付类型对应的费率
                if (!empty($value['payment_type_rate'])) {
                    $value['payment_type_rate'] = json_decode($value['payment_type_rate'], true);
                }
                // 支付类型每次最小充值金额
                if (!empty($value['min_recharge_cash'])) {
                    $value['min_recharge_cash'] = json_decode($value['min_recharge_cash'], true);
                }
                // 支付类型每次最大充值金额
                if (!empty($value['max_recharge_cash'])) {
                    $value['max_recharge_cash'] = json_decode($value['max_recharge_cash'], true);
                }
                // 支付类型对应的固定充值金额
                if (!empty($value['payment_type_cash'])) {
                    $value['payment_type_cash'] = json_decode($value['payment_type_cash'], true);
                    foreach ($value['payment_type_cash'] as $payment_type_cash_key => $payment_type_cash_value) {
                        $value['payment_type_cash'][$payment_type_cash_key] = $payment_type_cash_value ? explode(',', $payment_type_cash_value) : '';
                    }
                }

                // 绑定白名单商户号
                $value['bind_merchant'] = $value['bind_merchant'] ? explode(',', $value['bind_merchant']) : '';

                // 上游服务端通知IP白名单
                $value['notify_ip'] = $value['notify_ip'] ? explode(',', $value['notify_ip']) : '';

                $payment_redis = RedisModel::where(['name' => $key])->field(true)->find();
                if ($payment_redis) {
                    $update = RedisModel::where(['name' => $key])->update(['title' => $value['title'], 'value' => json_encode($value), 'sort' => $sort++, 'update_time' => time()]);
                } else {
                    $insert = RedisModel::create(['name' => $key, 'title' => $value['title'], 'value' => json_encode($value), 'sort' => $sort++, 'create_time' => time(), 'update_time' => time(), 'status' => $value['status']]);
                }
            }

            // 查询已经配置完成的银行卡支付宝代付公司配置
            $payment_paid_company = PaymentPaidCompanyModel::where([])->order(['group' => 'asc', 'sort' => 'asc', 'title' => 'asc', 'name' => 'asc'])->column('*', 'name');

            // 存在更新数据库，插入数据库,银行卡支付宝代付公司配置
            $sort = 400;
            foreach ($payment_paid_company as $key => $value) {

                // 绑定白名单商户号
                $value['bind_merchant'] = $value['bind_merchant'] ? explode(',', $value['bind_merchant']) : '';

                // 禁止姓名
                $value['deny_name'] = $value['deny_name'] ? explode(',', $value['deny_name']) : '';

                // 上游服务端通知IP白名单
                $value['notify_ip'] = $value['notify_ip'] ? explode(',', $value['notify_ip']) : '';

                $payment_redis = RedisModel::where(['name' => $key])->field(true)->find();
                if ($payment_redis) {
                    $update = RedisModel::where(['name' => $key])->update(['title' => $value['title'], 'value' => json_encode($value), 'sort' => $sort++, 'update_time' => time()]);
                } else {
                    $insert = RedisModel::create(['name' => $key, 'title' => $value['title'], 'value' => json_encode($value), 'sort' => $sort++, 'create_time' => time(), 'update_time' => time(), 'status' => $value['status']]);
                }
            }

            // 查询已经配置完成的银行卡提现公司配置
            $payment_withdrawal_company = PaymentWithdrawalCompanyModel::where([])->order(['group' => 'asc', 'sort' => 'asc', 'title' => 'asc', 'name' => 'asc'])->column('*', 'name');

            // 存在更新数据库，插入数据库,银行卡提现公司配置            
            $sort = 500;
            foreach ($payment_withdrawal_company as $key => $value) {

                // 上游服务端通知IP白名单
                $value['notify_ip'] = $value['notify_ip'] ? explode(',', $value['notify_ip']) : '';

                $payment_redis = RedisModel::where(['name' => $key])->field(true)->find();
                if ($payment_redis) {
                    $update = RedisModel::where(['name' => $key])->update(['title' => $value['title'], 'value' => json_encode($value), 'sort' => $sort++, 'update_time' => time()]);
                } else {
                    $insert = RedisModel::create(['name' => $key, 'title' => $value['title'], 'value' => json_encode($value), 'sort' => $sort++, 'create_time' => time(), 'update_time' => time(), 'status' => $value['status']]);
                }
            }

            // 获得支付类型
            $payment_types = pay_config('payment_type', 'pay_config');
            // 分开单个支付类型
            $sort = 600;
            foreach ($payment_types as $key => $value) {
                // 存在更新数据库，插入数据库,单个支付类型
                $payment_redis = RedisModel::where(['name' => $key])->field(true)->find();
                if ($payment_redis) {
                    $update = RedisModel::where(['name' => $key])->update(['title' => $value, 'value' => 1, 'sort' => $sort++, 'update_time' => time()]);
                } else {
                    $insert = RedisModel::create(['name' => $key, 'title' => $value, 'value' => 1, 'sort' => $sort++, 'create_time' => time(), 'update_time' => time(), 'status' => 1]);
                }
            }

            // 获得交易类型
            $trade_types = pay_config('trade_type', 'pay_config');
            // 分开单个交易类型
            $sort = 700;
            foreach ($trade_types as $key => $value) {
                // 存在更新数据库，插入数据库,单个交易类型
                $payment_redis = RedisModel::where(['name' => $key])->field(true)->find();
                if ($payment_redis) {
                    $update = RedisModel::where(['name' => $key])->update(['title' => $value, 'value' => 1, 'sort' => $sort++, 'update_time' => time()]);
                } else {
                    $insert = RedisModel::create(['name' => $key, 'title' => $value, 'value' => 1, 'sort' => $sort++, 'create_time' => time(), 'update_time' => time(), 'status' => 1]);
                }
            }

            // 获得支付开关
            $payment_open = pay_config('payment_open');
            // 存在更新数据库，插入数据库,支付类型配置
            $sort = 800;
            $payment_redis = RedisModel::where(['name' => 'payment_open'])->field(true)->find();
            if ($payment_redis) {
                $update = RedisModel::where(['name' => 'payment_open'])->update(['title' => '支付开关', 'value' => $payment_open, 'sort' => $sort++, 'update_time' => time()]);
            } else {
                $insert = RedisModel::create(['name' => 'payment_open', 'title' => '支付开关', 'value' => $payment_open, 'sort' => $sort++, 'create_time' => time(), 'update_time' => time(), 'status' => $payment_open]);
            }

            // 获得是否开启订单验证
            $order_verify = pay_config('order_verify');
            // 存在更新数据库，插入数据库,是否开启订单验证
            $sort = 900;
            $payment_redis = RedisModel::where(['name' => 'order_verify'])->field(true)->find();
            if ($payment_redis) {
                $update = RedisModel::where(['name' => 'order_verify'])->update(['title' => '订单验证开关', 'value' => $order_verify, 'sort' => $sort++, 'update_time' => time()]);
            } else {
                $insert = RedisModel::create(['name' => 'order_verify', 'title' => '订单验证开关', 'value' => $order_verify, 'sort' => $sort++, 'create_time' => time(), 'update_time' => time(), 'status' => $order_verify]);
            }

            // 获得代付绿色通道开关
            $paid_green_channel_open = pay_config('paid_green_channel_open');
            // 存在更新数据库，插入数据库,代付绿色通道开关
            $sort = 1000;
            $payment_redis = RedisModel::where(['name' => 'paid_green_channel_open'])->field(true)->find();
            if ($payment_redis) {
                $update = RedisModel::where(['name' => 'paid_green_channel_open'])->update(['title' => '代付绿色通道开关', 'value' => $paid_green_channel_open, 'sort' => $sort++, 'update_time' => time()]);
            } else {
                $insert = RedisModel::create(['name' => 'paid_green_channel_open', 'title' => '代付绿色通道开关', 'value' => $paid_green_channel_open, 'sort' => $sort++, 'create_time' => time(), 'update_time' => time(), 'status' => $paid_green_channel_open]);
            }

            // 全局代付银行支付宝金额限制开关
            $paid_cash_limit_open = pay_config('paid_cash_limit_open');
            // 存在更新数据库，插入数据库,全局代付银行支付宝金额限制开关
            $sort = 1100;
            $payment_redis = RedisModel::where(['name' => 'paid_cash_limit_open'])->field(true)->find();
            if ($payment_redis) {
                $update = RedisModel::where(['name' => 'paid_cash_limit_open'])->update(['title' => '全局代付银行支付宝金额限制开关', 'value' => $paid_cash_limit_open, 'sort' => $sort++, 'update_time' => time()]);
            } else {
                $insert = RedisModel::create(['name' => 'paid_cash_limit_open', 'title' => '全局代付银行支付宝金额限制开关', 'value' => $paid_cash_limit_open, 'sort' => $sort++, 'create_time' => time(), 'update_time' => time(), 'status' => $paid_cash_limit_open]);
            }

            // 获得邮箱发送错误开关
            $error_email_open = pay_config('error_email_open');
            // 存在更新数据库，插入数据库,邮箱发送错误开关
            $sort = 1200;
            $payment_redis = RedisModel::where(['name' => 'error_email_open'])->field(true)->find();
            if ($payment_redis) {
                $update = RedisModel::where(['name' => 'error_email_open'])->update(['title' => '邮箱发送错误开关', 'value' => $error_email_open, 'sort' => $sort++, 'update_time' => time()]);
            } else {
                $insert = RedisModel::create(['name' => 'error_email_open', 'title' => '邮箱发送错误开关', 'value' => $error_email_open, 'sort' => $sort++, 'create_time' => time(), 'update_time' => time(), 'status' => $error_email_open]);
            }

            // 获得错误邮箱列表
            $error_email_list = pay_config('error_email_list');
            // 存在更新数据库，插入数据库,错误邮箱列表
            $sort = 1300;
            $payment_redis = RedisModel::where(['name' => 'error_email_list'])->field(true)->find();
            if ($payment_redis) {
                $update = RedisModel::where(['name' => 'error_email_list'])->update(['title' => '错误邮箱列表', 'value' => json_encode($error_email_list), 'sort' => $sort++, 'update_time' => time()]);
            } else {
                $insert = RedisModel::create(['name' => 'error_email_list', 'title' => '错误邮箱列表', 'value' => json_encode($error_email_list), 'sort' => $sort++, 'create_time' => time(), 'update_time' => time(), 'status' => 1]);
            }

            // 商户号连续未支付订单报警开关
            $merchant_no_pay_warn_open = pay_config('merchant_no_pay_warn_open');
            // 存在更新数据库，插入数据库,商户号连续未支付订单报警开关
            $sort = 1400;
            $payment_redis = RedisModel::where(['name' => 'merchant_no_pay_warn_open'])->field(true)->find();
            if ($payment_redis) {
                $update = RedisModel::where(['name' => 'merchant_no_pay_warn_open'])->update(['title' => '商户号连续未支付订单报警开关', 'value' => $merchant_no_pay_warn_open, 'sort' => $sort++, 'update_time' => time()]);
            } else {
                $insert = RedisModel::create(['name' => 'merchant_no_pay_warn_open', 'title' => '商户号连续未支付订单报警开关', 'value' => $merchant_no_pay_warn_open, 'sort' => $sort++, 'create_time' => time(), 'update_time' => time(), 'status' => $merchant_no_pay_warn_open]);
            }

            // 商户号多少个连续未支付订单报警
            $merchant_no_pay_sum_warn = pay_config('merchant_no_pay_sum_warn');
            // 存在更新数据库，插入数据库,商户号多少个连续未支付订单报警
            $sort = 1500;
            $payment_redis = RedisModel::where(['name' => 'merchant_no_pay_sum_warn'])->field(true)->find();
            if ($payment_redis) {
                $update = RedisModel::where(['name' => 'merchant_no_pay_sum_warn'])->update(['title' => '商户号多少个连续未支付订单报警', 'value' => $merchant_no_pay_sum_warn, 'sort' => $sort++, 'update_time' => time()]);
            } else {
                $insert = RedisModel::create(['name' => 'merchant_no_pay_sum_warn', 'title' => '商户号多少个连续未支付订单报警', 'value' => $merchant_no_pay_sum_warn, 'sort' => $sort++, 'create_time' => time(), 'update_time' => time(), 'status' => 1]);
            }

            // 获得支付手机接收报警
            $payment_mobile_warn = pay_config('payment_mobile_warn');
            // 存在更新数据库，插入数据库,支付手机接收报警
            $sort = 1600;
            $payment_redis = RedisModel::where(['name' => 'payment_mobile_warn'])->field(true)->find();
            if ($payment_redis) {
                $update = RedisModel::where(['name' => 'payment_mobile_warn'])->update(['title' => '支付手机接收报警', 'value' => json_encode($payment_mobile_warn), 'sort' => $sort++, 'update_time' => time()]);
            } else {
                $insert = RedisModel::create(['name' => 'payment_mobile_warn', 'title' => '支付手机接收报警', 'value' => json_encode($payment_mobile_warn), 'sort' => $sort++, 'create_time' => time(), 'update_time' => time(), 'status' => 1]);
            }

            // 灰名单变黑名单ip个数
            $gray_change_black_ip = pay_config('gray_change_black_ip');
            // 存在更新数据库，插入数据库,灰名单变黑名单ip个数
            $sort = 1700;
            $payment_redis = RedisModel::where(['name' => 'gray_change_black_ip'])->field(true)->find();
            if ($payment_redis) {
                $update = RedisModel::where(['name' => 'gray_change_black_ip'])->update(['title' => '灰名单变黑名单ip个数', 'value' => $gray_change_black_ip, 'sort' => $sort++, 'update_time' => time()]);
            } else {
                $insert = RedisModel::create(['name' => 'gray_change_black_ip', 'title' => '灰名单变黑名单ip个数', 'value' => $gray_change_black_ip, 'sort' => $sort++, 'create_time' => time(), 'update_time' => time(), 'status' => 1]);
            }

            // 商品名称是订单号
            $body_order = pay_config('body_order');
            // 存在更新数据库，插入数据库,商品名称是订单号
            $sort = 1800;
            $payment_redis = RedisModel::where(['name' => 'body_order'])->field(true)->find();
            if ($payment_redis) {
                $update = RedisModel::where(['name' => 'body_order'])->update(['title' => '商品名称是订单号', 'value' => $body_order, 'sort' => $sort++, 'update_time' => time()]);
            } else {
                $insert = RedisModel::create(['name' => 'body_order', 'title' => '商品名称是订单号', 'value' => $body_order, 'sort' => $sort++, 'create_time' => time(), 'update_time' => time(), 'status' => $body_order]);
            }

            // 支付公司轮循开关
            $pay_polling_open = pay_config('pay_polling_open');
            // 存在更新数据库，插入数据库,支付公司轮循开关
            $sort = 1900;
            $payment_redis = RedisModel::where(['name' => 'pay_polling_open'])->field(true)->find();
            if ($payment_redis) {
                $update = RedisModel::where(['name' => 'pay_polling_open'])->update(['title' => '支付公司轮循开关', 'value' => $pay_polling_open, 'sort' => $sort++, 'update_time' => time()]);
            } else {
                $insert = RedisModel::create(['name' => 'pay_polling_open', 'title' => '支付公司轮循开关', 'value' => $pay_polling_open, 'sort' => $sort++, 'create_time' => time(), 'update_time' => time(), 'status' => $pay_polling_open]);
            }

            // 银行卡代付开关
            $bank_card_paid_open = pay_config('bank_card_paid_open');
            // 存在更新数据库，插入数据库,支付宝代付开关
            $sort = 2000;
            $payment_redis = RedisModel::where(['name' => 'bank_card_paid_open'])->field(true)->find();
            if ($payment_redis) {
                $update = RedisModel::where(['name' => 'bank_card_paid_open'])->update(['title' => '银行卡代付开关', 'value' => $bank_card_paid_open, 'sort' => $sort++, 'update_time' => time()]);
            } else {
                $insert = RedisModel::create(['name' => 'bank_card_paid_open', 'title' => '银行卡代付开关', 'value' => $bank_card_paid_open, 'sort' => $sort++, 'create_time' => time(), 'update_time' => time(), 'status' => $bank_card_paid_open]);
            }

            // 支付宝代付开关
            $alipay_paid_open = pay_config('alipay_paid_open');
            // 存在更新数据库，插入数据库,支付宝代付开关
            $sort = 2100;
            $payment_redis = RedisModel::where(['name' => 'alipay_paid_open'])->field(true)->find();
            if ($payment_redis) {
                $update = RedisModel::where(['name' => 'alipay_paid_open'])->update(['title' => '支付宝代付开关', 'value' => $alipay_paid_open, 'sort' => $sort++, 'update_time' => time()]);
            } else {
                $insert = RedisModel::create(['name' => 'alipay_paid_open', 'title' => '支付宝代付开关', 'value' => $alipay_paid_open, 'sort' => $sort++, 'create_time' => time(), 'update_time' => time(), 'status' => $alipay_paid_open]);
            }

            // 银行卡代付轮循开关
            $bank_paid_polling_open = pay_config('bank_paid_polling_open');
            // 存在更新数据库，插入数据库,银行卡代付轮循开关
            $sort = 2200;
            $payment_redis = RedisModel::where(['name' => 'bank_paid_polling_open'])->field(true)->find();
            if ($payment_redis) {
                $update = RedisModel::where(['name' => 'bank_paid_polling_open'])->update(['title' => '银行卡代付轮循开关', 'value' => $bank_paid_polling_open, 'sort' => $sort++, 'update_time' => time()]);
            } else {
                $insert = RedisModel::create(['name' => 'bank_paid_polling_open', 'title' => '银行卡代付轮循开关', 'value' => $bank_paid_polling_open, 'sort' => $sort++, 'create_time' => time(), 'update_time' => time(), 'status' => $bank_paid_polling_open]);
            }

            // 支付宝代付轮循开关
            $alipay_paid_polling_open = pay_config('alipay_paid_polling_open');
            // 存在更新数据库，插入数据库,支付宝代付轮循开关
            $sort = 2300;
            $payment_redis = RedisModel::where(['name' => 'alipay_paid_polling_open'])->field(true)->find();
            if ($payment_redis) {
                $update = RedisModel::where(['name' => 'alipay_paid_polling_open'])->update(['title' => '支付宝代付轮循开关', 'value' => $alipay_paid_polling_open, 'sort' => $sort++, 'update_time' => time()]);
            } else {
                $insert = RedisModel::create(['name' => 'alipay_paid_polling_open', 'title' => '支付宝代付轮循开关', 'value' => $alipay_paid_polling_open, 'sort' => $sort++, 'create_time' => time(), 'update_time' => time(), 'status' => $alipay_paid_polling_open]);
            }

            // 代付请求间隔
            $paid_request_interval = pay_config('paid_request_interval');
            // 存在更新数据库，插入数据库,代付请求间隔
            $sort = 2400;
            $payment_redis = RedisModel::where(['name' => 'paid_request_interval'])->field(true)->find();
            if ($payment_redis) {
                $update = RedisModel::where(['name' => 'paid_request_interval'])->update(['title' => '代付相同帐号请求间隔', 'value' => $paid_request_interval, 'sort' => $sort++, 'update_time' => time()]);
            } else {
                $insert = RedisModel::create(['name' => 'paid_request_interval', 'title' => '代付相同帐号请求间隔', 'value' => $paid_request_interval, 'sort' => $sort++, 'create_time' => time(), 'update_time' => time(), 'status' => 1]);
            }

            // 每天代付开始时间
            $paid_start_time = pay_config('paid_start_time');
            // 存在更新数据库，插入数据库,每天代付开始时间
            $sort = 2500;
            $payment_redis = RedisModel::where(['name' => 'paid_start_time'])->field(true)->find();
            if ($payment_redis) {
                $update = RedisModel::where(['name' => 'paid_start_time'])->update(['title' => '每天代付开始时间', 'value' => $paid_start_time, 'sort' => $sort++, 'update_time' => time()]);
            } else {
                $insert = RedisModel::create(['name' => 'paid_start_time', 'title' => '每天代付开始时间', 'value' => $paid_start_time, 'sort' => $sort++, 'create_time' => time(), 'update_time' => time(), 'status' => 1]);
            }

            // 每天代付结束时间
            $paid_end_time = pay_config('paid_end_time');
            // 存在更新数据库，插入数据库,每天代付结束时间
            $sort = 2600;
            $payment_redis = RedisModel::where(['name' => 'paid_end_time'])->field(true)->find();
            if ($payment_redis) {
                $update = RedisModel::where(['name' => 'paid_end_time'])->update(['title' => '每天代付结束时间', 'value' => $paid_end_time, 'sort' => $sort++, 'update_time' => time()]);
            } else {
                $insert = RedisModel::create(['name' => 'paid_end_time', 'title' => '每天代付结束时间', 'value' => $paid_end_time, 'sort' => $sort++, 'create_time' => time(), 'update_time' => time(), 'status' => 1]);
            }

            // 查询优质公司
            $payment_good_company = PaymentGoodCompanyModel::where(['status' => 1])->order('sort asc,id asc')->column('bind_merchant,payment_type', 'company_name');
            if ($payment_good_company) {
                foreach ($payment_good_company as $payment_good_company_key => $payment_good_company_value) {
                    if ($payment_good_company[$payment_good_company_key]['payment_type']) {
                        $payment_good_company[$payment_good_company_key]['payment_type'] = json_decode($payment_good_company[$payment_good_company_key]['payment_type'], true);
                    }
                    $payment_good_company[$payment_good_company_key]['bind_merchant'] = $payment_good_company[$payment_good_company_key]['bind_merchant'] ? explode(',', $payment_good_company[$payment_good_company_key]['bind_merchant']) : '';
                    unset($payment_good_company[$payment_good_company_key]['company_name']);
                }
            }
            // 存在更新数据库，插入数据库
            $sort = 2700;
            $payment_redis = RedisModel::where(['name' => 'all_good_company'])->field(true)->find();
            if ($payment_redis) {
                $update = RedisModel::where(['name' => 'all_good_company'])->update(['title' => '优质支付公司开关', 'value' => json_encode($payment_good_company), 'sort' => $sort++, 'update_time' => time()]);
            } else {
                $insert = RedisModel::create(['name' => 'all_good_company', 'title' => '优质支付公司开关', 'value' => json_encode($payment_good_company), 'sort' => $sort++, 'create_time' => time(), 'update_time' => time(), 'status' => 1]);
            }

            // 优质公司轮循开关
            $good_company_polling_open = pay_config('good_company_polling_open');
            // 存在更新数据库，插入数据库
            $sort = 2800;
            $payment_redis = RedisModel::where(['name' => 'good_company_polling_open'])->field(true)->find();
            if ($payment_redis) {
                $update = RedisModel::where(['name' => 'good_company_polling_open'])->update(['title' => '优质支付公司轮循开关', 'value' => $good_company_polling_open, 'sort' => $sort++, 'update_time' => time()]);
            } else {
                $insert = RedisModel::create(['name' => 'good_company_polling_open', 'title' => '优质支付公司轮循开关', 'value' => $good_company_polling_open, 'sort' => $sort++, 'create_time' => time(), 'update_time' => time(), 'status' => $good_company_polling_open]);
            }

            // 查询优质代付公司
            $payment_good_paid_company = PaymentGoodPaidCompanyModel::where(['status' => 1])->order('sort asc,id asc')->column('bind_merchant,paid_class', 'company_name');
            if ($payment_good_paid_company) {
                foreach ($payment_good_paid_company as $payment_good_paid_company_key => $payment_good_paid_company_value) {
                    if ($payment_good_paid_company[$payment_good_paid_company_key]['bind_merchant']) {
                        $payment_good_paid_company[$payment_good_paid_company_key]['bind_merchant'] = $payment_good_paid_company[$payment_good_paid_company_key]['bind_merchant'] ? explode(',', $payment_good_paid_company[$payment_good_paid_company_key]['bind_merchant']) : '';
                        unset($payment_good_paid_company[$payment_good_paid_company_key]['company_name']);
                    } else {
                        unset($payment_good_paid_company[$payment_good_paid_company_key]);
                    }
                }
            }
            // 存在更新数据库，插入数据库
            $sort = 2900;
            $payment_redis = RedisModel::where(['name' => 'all_good_paid_company'])->field(true)->find();
            if ($payment_redis) {
                $update = RedisModel::where(['name' => 'all_good_paid_company'])->update(['title' => '优质代付公司开关', 'value' => json_encode($payment_good_paid_company), 'sort' => $sort++, 'update_time' => time()]);
            } else {
                $insert = RedisModel::create(['name' => 'all_good_paid_company', 'title' => '优质代付公司开关', 'value' => json_encode($payment_good_paid_company), 'sort' => $sort++, 'create_time' => time(), 'update_time' => time(), 'status' => 1]);
            }

            // 优质代付公司轮循开关
            $good_paid_company_polling_open = pay_config('good_paid_company_polling_open');
            // 存在更新数据库，插入数据库
            $sort = 3000;
            $payment_redis = RedisModel::where(['name' => 'good_paid_company_polling_open'])->field(true)->find();
            if ($payment_redis) {
                $update = RedisModel::where(['name' => 'good_paid_company_polling_open'])->update(['title' => '优质代付公司轮循开关', 'value' => $good_paid_company_polling_open, 'sort' => $sort++, 'update_time' => time()]);
            } else {
                $insert = RedisModel::create(['name' => 'good_paid_company_polling_open', 'title' => '优质代付公司轮循开关', 'value' => $good_paid_company_polling_open, 'sort' => $sort++, 'create_time' => time(), 'update_time' => time(), 'status' => $good_paid_company_polling_open]);
            }

            // 令牌token
            $token = pay_config('token');
            // 存在更新数据库，插入数据库,令牌token
            $sort = 3100;
            $payment_redis = RedisModel::where(['name' => 'token'])->field(true)->find();
            if ($payment_redis) {
                $update = RedisModel::where(['name' => 'token'])->update(['title' => '令牌token', 'value' => $token, 'sort' => $sort++, 'update_time' => time()]);
            } else {
                $insert = RedisModel::create(['name' => 'token', 'title' => '令牌token', 'value' => $token, 'sort' => $sort++, 'create_time' => time(), 'update_time' => time(), 'status' => 1]);
            }

            // 获得redis开关
            $redis_open = pay_config('redis_open');
            // 存在更新数据库，插入数据库,redis开关
            $sort = 3200;
            $payment_redis = RedisModel::where(['name' => 'redis_open'])->field(true)->find();
            if ($payment_redis) {
                $update = RedisModel::where(['name' => 'redis_open'])->update(['title' => 'redis开关', 'value' => $redis_open, 'sort' => $sort++, 'update_time' => time()]);
            } else {
                $insert = RedisModel::create(['name' => 'redis_open', 'title' => 'redis开关', 'value' => $redis_open, 'sort' => $sort++, 'create_time' => time(), 'update_time' => time(), 'status' => $redis_open]);
            }

            action_log('payment_redis_sql', 'payment_redis', '', UID, '更新了redis数据库');

            // 同时更新了redis数据库和缓存
            if ($redisUp) {
                // 查询redis数据库
                $redis_config = RedisModel::where([])->order(['name' => 'asc'])->column('*', 'name');
                foreach ($redis_config as $k => &$v) {
                    //json转换成数组
                    if (!is_null(json_decode($v['value']))) {
                        $v['value'] = json_decode($v['value'], true);
                    }
                    // 存入redis缓存中
                    $this->redis->set($k, $v);
                    // 存入文件缓存中
                    // $this->file->set($k, $v);
                }
                action_log('payment_redis_edit', 'payment_redis', '', UID, '同时更新了redis数据库和缓存');
            }

            // 更新代付余额
            if ($paidCashUp) {

                $map = [];
                $map[] = ['status', '=', 1];
                $map[] = ['paid_class', '=', 1];

                $all_child_company = PaymentPaidCompanyModel::where($map)
                    ->order(['group' => 'asc', 'sort' => 'asc', 'title' => 'asc', 'name' => 'asc'])
                    ->column('*', 'name');

                foreach ($all_child_company as $company_k => $company_v) {

                    $company_parent_name = strstr($company_k, 'Paid', true);

                    $companys = $company_parent_name . 'PaidQueryCash';

                    // 实例化第三方订单模型
                    if ($company_v['paid_class'] == 0) {
                        $other_order_obj = new PaymentOrderPaid();
                    } else {
                        $other_order_obj = new PaymentOrderAlipayPaid();
                    }

                    // 发送给第三方支付公司订单号    
                    $resarray = $other_order_obj->$companys($company_v);

                    if ($resarray['code'] == 200) {

                        $now_day = date('Y-m-d');
                        $temp = [];
                        $temp[] = ['child_company', '=', $company_k];
                        $temp[] = ['status', '=', 2];
                        $temp[] = ['create_time', 'between time', ["$now_day 00:00:00", "$now_day 23:59:59"]];
                        if ($company_v['paid_class'] == 0) {
                            $now_order_cash_ok = PaymentOrderPaid::where($temp)->sum('cash');
                        } else {
                            $now_order_cash_ok = PaymentOrderAlipayPaid::where($temp)->sum('cash');
                        }
                        $now_order_cash_ok /= 100;

                        $cash = intval($resarray['cash']) + $now_order_cash_ok;

                        PaymentPaidCompanyModel::where(['name' => $company_k])
                            ->update(['day_paid_cash_sum' => $cash, 'update_time' => time()]);

                        // 更新redis
                        $redis_find = RedisModel::where(['name' => $company_k])->find();
                        if ($redis_find) {

                            if (!is_null(json_decode($redis_find['value']))) {
                                $redis_temp_v = json_decode($redis_find['value'], true);
                                $redis_temp_v['day_paid_cash_sum'] = $cash;

                                RedisModel::where(['name' => $company_k])
                                    ->update(['value' => json_encode($redis_temp_v), 'status' => 1, 'update_time' => time()]);
                            }

                            $redis_config = RedisModel::where(['name' => $company_k])
                                ->order(['name' => 'asc'])
                                ->column('*', 'name');
                            foreach ($redis_config as $k => &$v) {
                                //json转换成数组
                                if (!is_null(json_decode($v['value']))) {
                                    $v['value'] = json_decode($v['value'], true);
                                }
                                $this->redis->set($k, $v);
                            }
                        }
                    } else {
                        // 查询余额错误
                    }
                }

                action_log('payment_redis_edit', 'payment_redis', '', UID, '更新代付余额');
            }

            $this->success('更新完成', url('index'));
        }

        $items = [
            ['password', 'trade_pwd', '交易密码', '6-16位'],
        ];

        // 使用ZBuilder快速创建表单
        return ZBuilder::make('form')
            ->setPageTitle('同时更新redis数据库和文件缓存') // 设置页面标题
            ->addFormItems($items)
            ->fetch();
    }

    /**
     * 更新数据库redis
     */
    public function redisUp()
    {
        // 保存数据
        if ($this->request->isPost()) {
            $data = $this->request->post();

            if ($this->merchant_info['trade_pwd'] != md5(md5(md5($data['trade_pwd'])))) {
                $this->error('交易密码不正确！');
            }

            unset($data['trade_pwd']);

            // 查询redis数据库
            $redis_config = RedisModel::where([])->order(['name' => 'asc'])->column('*', 'name');

            foreach ($redis_config as $k => &$v) {
                //json转换成数组
                if (!is_null(json_decode($v['value']))) {
                    $v['value'] = json_decode($v['value'], true);
                }

                //dump($v);
                // 存入redis缓存中
                $this->redis->set($k, $v);
                // 存入文件缓存中
                // $this->file->set($k, $v);
            }
            // exit;
            action_log('payment_redis_redisup', 'payment_redis', '', UID, '更新了redis缓存');
            $this->success('更新完成', url('index'));
        }

        $items = [
            ['password', 'trade_pwd', '交易密码', '6-16位'],
        ];

        // 使用ZBuilder快速创建表单
        return ZBuilder::make('form')
            ->setPageTitle('更新数据库redis') // 设置页面标题
            ->addFormItems($items)
            ->fetch();
    }

    /**
     * 更新
     * @param null $id 
     * @return mixed
     */
    public function update($id = null)
    {
        if ($id === null) {
            $this->error('缺少参数！');
        }

        // 保存数据
        if ($this->request->isPost()) {
            $data = $this->request->post();

            if ($this->merchant_info['trade_pwd'] != md5(md5(md5($data['trade_pwd'])))) {
                $this->error('交易密码不正确！');
            }

            unset($data['trade_pwd']);

            // 查询redis数据库
            $redis_config = RedisModel::where(['id' => $id])->order(['name' => 'asc'])->column('*', 'name');
            if (empty($redis_config)) {
                $this->error('空数据！');
            }

            foreach ($redis_config as $k => &$v) {
                //json转换成数组
                if (!is_null(json_decode($v['value']))) {
                    $v['value'] = json_decode($v['value'], true);
                }
                $this->redis->set($k, $v);
                // $this->file->set($k, $v);
            }
            action_log('payment_redis_update', 'payment_redis', '', UID, json_encode($v));
            $this->success('更新完成', url('index'));
        }

        $items = [
            ['password', 'trade_pwd', '交易密码', '6-16位'],
        ];

        // 使用ZBuilder快速创建表单
        return ZBuilder::make('form')
            ->setPageTitle('更新') // 设置页面标题
            ->addFormItems($items)
            ->fetch();
    }

    /**
     * 删除
     * @param array $record 
     * @return mixed
     */
    public function delete($record = [])
    {
        return $this->setStatus('delete');
    }

    /**
     * 启用
     * @param array $record 
     * @return mixed
     */
    public function enable($record = [])
    {
        return $this->setStatus('enable');
    }

    /**
     * 禁用
     * @param array $record 
     * @return mixed
     */
    public function disable($record = [])
    {
        return $this->setStatus('disable');
    }

    /**
     * 设置状态：删除、禁用、启用
     * @param string $type 类型：delete/enable/disable
     * @param array $record 
     * @return mixed
     */
    public function setStatus($type = '', $record = [])
    {
        $ids = $this->request->isPost() ? input('post.ids/a') : input('param.ids');
        $ids_delete = is_array($ids) ? '' : $ids;
        $data = RedisModel::where('id', 'in', $ids)->column('id');
        return parent::setStatus($type, ['payment_redis_' . $type, 'payment_redis', $ids_delete, UID, implode('、', $data)]);
    }

    /**
     * 快速编辑
     * @param array $record 行为日志
     * @return mixed
     */
    public function quickEdit($record = [])
    {
        $id = input('post.pk', '');
        $field = input('post.name', '');
        $value = input('post.value', '');
        $data = RedisModel::where('id', $id)->value($field);
        $details = '字段(' . $field . ')，原值(' . $data . ')，新值：(' . $value . ')';
        return parent::quickEdit(['payment_redis_edit', 'payment_redis', $id, UID, $details]);
    }
}
